﻿using System;
using UnityEngine;

namespace JH
{
    public static class GetComponentInParentRealization
    {
        /// <summary>
        /// 从祖先节点上获取脚本或者接口，不检测自己，检测顺序是父节点 -> 父节点的父节点 -> 父节点的父节点的父节点 -> ...
        /// </summary>
        public static T GetComponentInParentEm<T>(this GameObject go) where T : class
        {
            if (go == null)
                throw new ArgumentNullException(nameof(go), "必须传入一个游戏物体，才能获取祖先节点上的脚本！");

            var current = go.transform.parent;
            while (current != null)
            {
                if (current.TryGetComponent(out T component))
                    return component;

                current = current.parent;
            }

            return null;
        }
    }
}